package com.example.listviewtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class AnimalRecyclerAdapter extends RecyclerView.Adapter {
    private ArrayList<Animal> animals;

    public AnimalRecyclerAdapter(ArrayList<Animal> animals) {
        this.animals = animals;
    }

    //内部类
    static class AnimalViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView textView;
        public AnimalViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.animal,parent,false);
        AnimalViewHolder animalViewHolder = new AnimalViewHolder(view);
        animalViewHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(parent.getContext(), "position:"+viewType,Toast.LENGTH_SHORT).show();
            }
        });
        return animalViewHolder;
    }

    @Override
    public int getItemViewType(int position) {
        return  position;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Animal animal = animals.get(position);
        ((AnimalViewHolder) holder).imageView.setImageResource(animal.getPicID());
        ((AnimalViewHolder) holder).textView.setText(animal.getName());
    }

    @Override
    public int getItemCount() {
        return animals.size();
    }
}
